package com.example.aicloud.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.net.NetUtil;
import cn.hutool.crypto.SecureUtil;
import com.example.aicloud.util.MinioUtil;
import com.example.aicloud.util.NameUtil;
import com.example.aicloud.util.ResponseEntity;
import io.minio.errors.*;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/captcha")
public class CaptchaController {
    @Resource
    private MinioUtil minioUtil;
    @Resource
    private RedisTemplate redisTemplate;
    /**
     * 生成验证码
     */
    @RequestMapping("/create")
    public ResponseEntity createCaptcha(HttpServletRequest request) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {

        String url ="";
        // 定义图形验证码的长和宽
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(120, 40);
        // 因为验证码只使用一次，用过之后不删除的话对磁盘压力较大，所以使用用户的IP地址作为文件名，Minio在上传文件名重复的文件时会进行覆盖
        String fileName = NameUtil.getCaptchaName(request);
        try (InputStream inputStream = new ByteArrayInputStream(lineCaptcha.getImageBytes())){
            // 上传图片验证码到Minio
            url =minioUtil.upload(fileName, inputStream, "image/png");
            // 正确的验证码
            String code = lineCaptcha.getCode();
            // 存储到Redis中
            redisTemplate.opsForValue().set(fileName,code,60, TimeUnit.SECONDS);
        }
        return ResponseEntity.success(url);
    }
}
